<!--src/views/cases/AddCase.vue-->
<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import caseAPI from '@/api/case' // 引入案件API
import '@/styles/addcase.css'

const caseTypeOptions = [ // 修改为使用API枚举值的格式
  { value: '1', label: '民事案件' },
  { value: '2', label: '刑事案件' },
  { value: '3', label: '行政案件' },
  { value: '4', label: '其他案件' }
]

const currentStep = ref(1)
const selectedCaseType = ref('') // 现在存储的是值如'1'而不是标签
const caseDescription = ref('')
const files = ref([])
const isLoading = ref(false)
const isDragging = ref(false)

// 定义发射事件
const emit = defineEmits(['completed'])

// 在onMounted中添加全局监听
onMounted(() => {
  // 防止浏览器默认打开文件的行为
  document.addEventListener('dragover', (e) => {
    e.preventDefault()
  }, false)

  document.addEventListener('drop', (e) => {
    e.preventDefault()
  }, false)
})

// 修改后的拖拽处理方法
const handleDragOver = (e) => {
  e.preventDefault()
  e.stopPropagation()
  isDragging.value = true
}

const handleDragLeave = (e) => {
  e.preventDefault()
  e.stopPropagation()
  isDragging.value = false
}

const handleDrop = (e) => {
  e.preventDefault()
  e.stopPropagation()
  isDragging.value = false

  if (e.dataTransfer.files?.length) {
    handleFiles(e.dataTransfer.files)
  }
}

const handleFileChange = (event) => {
  if (event.target.files && event.target.files.length > 0) {
    handleFiles(event.target.files)
  }
  event.target.value = '' // 重置input，允许重复选择相同文件
}

// 统一处理文件添加逻辑
const handleFiles = (fileList) => {
  const newFiles = Array.from(fileList)
      .filter(file =>
          !files.value.some(f =>
              f.name === file.name &&
              f.size === file.size &&
              f.lastModified === file.lastModified
          )
      )
      .filter(file => {
        // 检查文件类型，只允许特定类型
        const allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
        const isAllowed = allowedTypes.some(type => file.type.includes(type))
        if (!isAllowed) {
          ElMessage.warning(`文件 ${file.name} 类型不被支持`)
        }
        return isAllowed
      })
      .filter(file => {
        // 检查文件大小，限制为10MB
        const maxSize = 10 * 1024 * 1024 // 10MB
        if (file.size > maxSize) {
          ElMessage.warning(`文件 ${file.name} 超过10MB限制`)
          return false
        }
        return true
      })

  if (newFiles.length > 0) {
    files.value = [...files.value, ...newFiles]
    ElMessage.success(`成功添加 ${newFiles.length} 个文件`)
  } else {
    ElMessage.warning('没有可添加的有效文件')
  }
}

// 改进的文件删除功能
const removeFile = async (index) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除文件 "${files.value[index].name}" 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    const removedFile = files.value.splice(index, 1)[0]
    ElMessage.success(`已删除文件: ${removedFile.name}`)
  } catch {
    // 用户取消删除
  }
}

// 清空所有文件
const clearAllFiles = async () => {
  if (files.value.length === 0) {
    ElMessage.warning('没有文件可清空')
    return
  }

  try {
    await ElMessageBox.confirm(
        '确定要清空所有文件吗？此操作不可撤销',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    files.value = []
    ElMessage.success('已清空所有文件')
  } catch {
    // 用户取消清空
  }
}

const nextStep = () => {
  if (currentStep.value === 1 && !selectedCaseType.value) {
    ElMessage.warning('请选择案件类型')
    return
  }
  if (currentStep.value === 2 && !caseDescription.value.trim()) {
    ElMessage.warning('请输入案情描述')
    return
  }
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

// 验证表单数据
const validateForm = () => {
  if (!selectedCaseType.value) {
    ElMessage.warning('请选择案件类型')
    currentStep.value = 1
    return false
  }

  if (!caseDescription.value.trim()) {
    ElMessage.warning('请输入案情描述')
    currentStep.value = 2
    return false
  }

  if (files.value.length === 0) {
    ElMessage.warning('请至少上传一个文件')
    currentStep.value = 3
    return false
  }

  return true
}

// 提交案件申请 - 使用真实API
const submitApplication = async () => {
  // 先验证表单数据
  if (!validateForm()) {
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在提交，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  isLoading.value = true

  try {
    // 准备API请求数据
    const formData = {
      caseType: selectedCaseType.value,
      description: caseDescription.value,
      attachments: files.value.map(file => ({
        name: file.name,
        size: file.size,
        type: file.type
      }))
    }

    // 调用真实API
    const response = await caseAPI.createCase(formData)

    if (response.code === 200) {
      ElMessage.success({
        message: '案件申请提交成功！',
        duration: 5000,
        showClose: true
      })

      // 重置表单
      currentStep.value = 1
      selectedCaseType.value = ''
      caseDescription.value = ''
      files.value = []

      // 提交完成后切换到列表标签页
      emit('completed')
    } else {
      throw new Error(response.message || '提交失败，请重试')
    }
  } catch (error) {
    console.error('提交错误:', error)
    ElMessage.error('提交失败: ' + (error.message || '未知错误'))
  } finally {
    loadingInstance.close()
    isLoading.value = false
  }
}

const isLastStep = computed(() => currentStep.value === 3)

// 返回列表标签页
const backToList = () => {
  emit('back-to-list')
}
</script>

<template>
  <div class="case-application">
    <!-- 移除了顶部标题 -->

    <!-- 步骤指示器 -->
    <div class="steps">
      <div
          v-for="(step, index) in 3"
          :key="index"
          :class="['step', { 'active': currentStep === index + 1, 'completed': currentStep > index + 1 }]"
          @click="currentStep = index + 1"
      >
        <div class="step-number">{{ index + 1 }}</div>
        <div class="step-title">
          {{
            index === 0 ? '案件类型' : (index === 1 ? '案情描述' : '上传材料')
          }}
        </div>
      </div>
      <div class="step-line" :style="{ width: `${(currentStep - 1) * 50}%` }"></div>
    </div>

    <!-- 步骤内容 -->
    <transition name="fade-slide" mode="out-in">
      <div class="step-content" v-if="currentStep === 1" key="step1">
        <h2>选择案件类型</h2>
        <div class="case-type-options">
          <div
              v-for="(type, index) in caseTypeOptions"
              :key="index"
              :class="['case-type', { 'selected': selectedCaseType === type.value }]"
              @click="selectedCaseType = type.value"
          >
            {{ type.label }}
          </div>
        </div>
      </div>

      <div class="step-content" v-else-if="currentStep === 2" key="step2">
        <h2>案情描述</h2>
        <textarea
            v-model="caseDescription"
            placeholder="请详细描述案情经过、相关人员和您的诉求..."
            rows="8"
        ></textarea>
        <div class="description-tips">
          <p>提示：</p>
          <ul>
            <li>请尽量详细描述事件经过</li>
            <li>注明时间、地点和相关人员</li>
            <li>明确您的诉求</li>
          </ul>
        </div>
      </div>

      <div class="step-content" v-else key="step3">
        <h2>上传材料</h2>
        <div
            class="upload-area"
            :class="{ 'dragging': isDragging }"
            @dragover="handleDragOver"
            @dragleave="handleDragLeave"
            @drop="handleDrop"
        >
          <label for="file-upload" class="upload-btn">
            <i class="el-icon-upload"></i>
            <span>点击或拖拽文件到此处</span>
            <input
                id="file-upload"
                type="file"
                multiple
                @change="handleFileChange"
                style="display: none;"
            >
          </label>
          <div class="upload-hint" v-show="isDragging">释放鼠标以添加文件</div>
          <div class="file-types-hint">
            支持格式: PDF, JPG, PNG, DOC, DOCX (最大10MB)
          </div>

          <div class="file-list-container" v-if="files.length > 0">
            <div class="file-list-header">
              <span>已选文件 ({{ files.length }})</span>
              <button class="clear-all-btn" @click="clearAllFiles">清空全部</button>
            </div>
            <div class="file-list">
              <div v-for="(file, index) in files" :key="index" class="file-item">
                <div class="file-info">
                  <i class="el-icon-document"></i>
                  <div class="file-details">
                    <span class="file-name">{{ file.name }}</span>
                    <span class="file-size">{{ (file.size / 1024 / 1024).toFixed(2) }} MB</span>
                  </div>
                </div>
                <i class="el-icon-close" @click="removeFile(index)"></i>
              </div>
            </div>
          </div>
          <div v-else class="empty-tip">暂无文件</div>
        </div>
      </div>
    </transition>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button
          v-if="currentStep === 1"
          class="btn prev-btn"
          @click="backToList"
          :disabled="isLoading"
      >
        返回列表
      </button>
      <button
          class="btn prev-btn"
          @click="prevStep"
          v-if="currentStep > 1"
          :disabled="isLoading"
      >
        上一步
      </button>
      <button
          class="btn next-btn"
          @click="nextStep"
          v-if="!isLastStep"
          :disabled="isLoading"
      >
        下一步
      </button>
      <button
          class="btn submit-btn"
          @click="submitApplication"
          v-else
          :disabled="isLoading"
      >
        <span v-if="!isLoading">提交申请</span>
        <span v-else>提交中...</span>
      </button>
    </div>
  </div>
</template>

<style scoped>
.case-application {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-buttons {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>